﻿using Avalonia;
using Avalonia.Controls;

namespace Digitalmes.AvaloniaUI.Infrastructure;

/// <summary>
/// ViewModel 基础类，实现该类的对象会被注入到服务中。
/// </summary>
public abstract class ViewModelBase : ObservableObject, IViewToViewModelBridge
{
    private readonly WeakReference<Visual?> _visualRef = new(default);

    Visual? IViewToViewModelBridge.View
    {
        get => _visualRef.TryGetTarget(out var target) ? target : default;
        set  
        { 
            _visualRef.SetTarget(value);
            BoundView();
        }
    }

    /// <summary>
    /// 通过 ViewLocator，将 View 注入 ViewModel 中，以便能获取 TopLevel。
    /// </summary>
    public TopLevel? TopLevel
    {
        get
        {
            if (_visualRef.TryGetTarget(out var view) && view is not null)
            {
                return TopLevel.GetTopLevel(view);
            }
            return default;
        }
    }

    /// <summary>
    /// 绑定 View 后要处理的事件。
    /// </summary>
    protected virtual void BoundView() 
    { 
    }
}
